package org.jeecg.modules.network.network.tcp;

import com.zhouwr.common.enums.MessageType;
import com.zhouwr.common.message.ReceiveMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.device.entity.DeviceInstance;
import org.jeecg.modules.device.listener.event.InstanceNotFindEvent;
import org.jeecg.modules.device.listener.event.InstanceReceiveDataEvent;
import org.jeecg.modules.device.service.impl.DeviceInstanceServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * Tcp服务器接收处理程序
 *
 * @author zhouwenrong
 * @date 2020/02/23 21:08
 */
@Slf4j
@Component
public class TcpServerReceiveHandler extends ChannelInboundHandlerAdapter {

    private static TcpServerReceiveHandler receiveHandler;

    @Autowired
    private DeviceInstanceServiceImpl instanceService;
    @Autowired
    private ApplicationEventPublisher publisher;

    /**************
     *
     * @param ctx
     * @param object
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object object) throws Exception {
        log.debug(">>>>> Tcp服务器接收处理程序 >>> TcpServerReceiveHandler <<<<<<");
        try {
            ReceiveMessage receiveMessage = (ReceiveMessage) object;
//            log.info("接收数据解析：{}", receiveMessage.toString());

            // 拿到传过来的msg数据，开始处理
            if (MessageType.HEART.getCode().equals(receiveMessage.getType())) {
                // 心跳数据直接返回
                ctx.writeAndFlush(System.currentTimeMillis());
            } else if (MessageType.DATA.getCode().equals(receiveMessage.getType())) {
                // 判断传感器有效
                int count = receiveHandler.instanceService.lambdaQuery()
                        .eq(DeviceInstance::getId, receiveMessage.getInstanceId())
                        .eq(DeviceInstance::getStatus, "online")
                        .count();
                if (count == 1) {
                    receiveHandler.publisher.publishEvent(new InstanceReceiveDataEvent(receiveMessage.getInstanceId(), receiveMessage.getDataMap()));
                } else {
                    receiveHandler.publisher.publishEvent(new InstanceNotFindEvent(receiveMessage.getInstanceId()));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @PostConstruct
    public void init() {
        receiveHandler = this;
        receiveHandler.instanceService = this.instanceService;
        receiveHandler.publisher = this.publisher;
    }

}
